<?php
/**
 * 中文验证码生成类.
 * 可以生成中文的验证码.需要字体支持. 
 */
class ValidateCodeModel {
	protected $font_dir = '';
	
	protected $font_file = '';
	
	public function __construct() {
		$this->font_dir = APP_ROOT . DIRECTORY_SEPARATOR . 'fonts';
		$this->font_file = $this->font_dir . DIRECTORY_SEPARATOR . 'simhei.ttf';
		if (file_exists($this->font_file) == FALSE) throw new Exception('验证码字体文件不存在.', 10001);
	}
	
	public function createValidateCodeImage($text) {
		// 创建图片
		$im = imagecreatetruecolor(200, 70);
		// 创建颜色
		$backcolor = imagecolorallocate($im, 244, 69, 0);        //设置背景为红色.
		$white = imagecolorallocate($im, mt_rand(180,255), mt_rand(180,255), mt_rand(0,100));       //文字字体为白色.
		imagefilledrectangle($im, 0, 0, 199, 69, $backcolor);   //设置背景色.
		// 文字添加到图片.
		imagettftext($im, 20, 10, 55, 50, $white, $this->font_file, $text);
		//显示PNG图片.
		imagepng($im);
		imagedestroy($im);
	}
	
	public function getRandCode($length = 3) {
		$validate_code = '';
		$ChineseChar = array("人","出","来","友","学","孝","仁","义","礼","廉","忠","国","中","易","白","者","火","土","金","木","雷","风","龙","虎","天","地","生","晕","菜","鸟","田","三","百","钱","福","爱","情","兽","虫","鱼","九","网","新","度","哎","唉","啊","哦","仪","老","少","日","月","星");
		for ($i = 0; $i < $length; $i++) $validate_code .= trim($ChineseChar[array_rand($ChineseChar)]);
		
		return $validate_code;
	}
	
	public function getFont() {
		return $this->font_file;
	}
}